auto();
var appPackgeName = ""; // "com.weaver.emobile7"
var appName = "" // EMobile7
//launchApp(appName) 

//closeApp(appPackgeName);

// 用法：
// 启动监听
// setupNotificationListener(qqNotificationHandler);
// simpleClickByBounds([404, 1040, 220, 1200]); // 

// waitForClockBtn();
//  analyzeLayout();
// 调试两个元素
// debugElement("外勤打卡");
// debugElement("考勤打卡");
// simpleClickByBounds([352, 1530, 720, 1700]); // 


// debugElement("外勤签到");
//debugElement("提交");



// 调试函数，输出元素详细信息
function debugElement(text) {
    var obj = selector().text(text).findOne(1000);
    if (obj) {
        var bounds = obj.bounds();
        log("=== " + text + " 元素信息 ===");
        log("是否存在: true");
        log("是否可见: " + obj.visibleToUser());
        log("是否可点击: " + obj.clickable());
        log("enabled: " + obj.enabled());
        log("focusable: " + obj.focusable());
        log("depth: " + obj.depth());

        log("边界信息: " + JSON.stringify(bounds));
        log("中心点坐标: " + bounds.centerX() + ", " + bounds.centerY());
        log("是否在屏幕内: " + (bounds.centerX() >= 0 && bounds.centerX() <= device.width &&
            bounds.centerY() >= 0 && bounds.centerY() <= device.height));
        //  log("父元素可见性: " + isParentVisible(obj));
        log("==================");
    } else {
        log(text + " 元素未找到");
    }
    //  obj.click();
}


// 打印界面结构，帮助分析
function analyzeLayout() {
    var allTexts = textMatches(".*").find();
    allTexts.forEach(function (t) {
        console.log("ID: " + t.id());

        console.log("文本: " + t.text() + ", 类型: " + t.className());
        console.log("坐标: " + t.bounds());
    });
}

function waitForClockBtn() {
    console.log(selector().text("外勤打卡").exists());
    console.log(selector().text("考勤打卡").exists());


    console.log(selector().text("外勤打卡").findOne(1000).clickable());
    console.log(selector().text("考勤打卡").findOne(1000).clickable());


    var reTry = 0;
    while (selector().text("外勤打卡").exists() || selector().text("考勤打卡").exists()) {
        swipeToBottom();
        sleep(1000);
        reTry++;
        if (reTry > 3) {
            break;
        }
    }
}


//app应用关闭
function closeApp(appPackgeName) {
    app.openAppSetting(appPackgeName);
    sleep(random(1000, 2000));
    text(app.getAppName(appPackgeName)).waitFor();
    // let is_sure = textMatches(/(.*强.*|.*停,*|.*結.*|.*行.*)/).findOne();
    let is_sure = text("强制停止").findOne();

    if (is_sure.enabled()) {
        // textMatches(/(.*强,*|.停,*|.*结,*|,*行,*)/).findOne().click();
        text("强制停止").findOne().click();
        textMatches(/(.*确,*|.*定.*)/).findOne().click();
        sleep(1000);
        console.log("应用已被关闭");
        sleep(2000);

        back();
    } else {
        console.log("应用不能被正常关闭或不在后台运行.");
        back();
        sleep(random(1000, 2000));
    }
}

// 锁屏
function lockScreen() {
    runtime.accessibilityBridge.getService().performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_LOCK_SCREEN);
}


// 监听事件
function setupNotificationListener(callback) {
    var success = false;

    // 方法1: 直接尝试开启
    try {
        events.observeNotification();
        events.on("notification", callback);
        console.log("通过方法-开启通知监听成功");
        success = true;
    } catch (e) {
        console.log("方法-失败: " + e.message);
    }

    // 如果方法1失败，提示用户手动设置
    if (!success) {
        console.log("请手动开启通知监听权限:");
        console.log("1. 打开手机设置");
        console.log("2. 找到'通知管理'或'通知使用权'");
        console.log("3. 找到Auto.js并开启权限");

        try {
            // 尝试跳转到设置页面
            app.startActivity({
                action: "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"
            });
        } catch (e) {
            console.log("无法自动跳转设置页面");
        }
    }

    return success;
}

// QQ通知处理函数
function qqNotificationHandler(notification) {
    if (notification.getPackageName() == "com.tencent.mobileqq") {
        console.log("=== 收到QQ通知 ===");
        console.log("时间: " + new Date().toLocaleString());
        console.log("标题: " + (notification.title || "无"));
        var text = notification.text || "无";
        console.log("内容: " + text);
        // 使用立即执行函数确保顺序执行
        (function () {
            try {
                console.log("开始执行打卡流程");
                clockIn(); // 打卡
                console.log("打卡流程执行完成");
            } catch (error) {
                console.log("发生了错误: " + error);
                closeApp(); // 关闭app
            } finally {

            }
        })();


        // 同步方法2，还没测试
        // setTimeout(function () {
        //     executeClockInSequence();
        //  }, 100);

    }
}

// 同步方法2
function executeClockInSequence() {
    try {
        console.log("开始顺序执行打卡流程");

        // 严格按照顺序执行每个步骤
        stepByStepClockIn();

    } catch (error) {
        console.log("执行过程中发生错误: " + error);
        // 错误处理也按顺序执行
        stepByStepCloseApp();
    }
}






// 根据坐标点击
function simpleClickByBounds(boundsInfo) {
    var left = boundsInfo[0];
    var top = boundsInfo[1];
    var right = boundsInfo[2];
    var bottom = boundsInfo[3];

    var x = Math.floor((left + right) / 2);
    var y = Math.floor((top + bottom) / 2);

    console.log("点击工作台按钮: (" + x + ", " + y + ")");
    // 执行点击
    var clickResult = click(x, y);
    if (!clickResult) {
        console.log("点击执行失败");
        return false;
    } else {
        return true;
    }
}






// 划到最下面
function swipeToBottom(counts) {
    counts = counts || 4;
    log("========================");

    log(counts);
    var screenWidth = device.width;
    var screenHeight = device.height;

    console.log("屏幕尺寸: " + screenWidth + " x " + screenHeight);

    // 多次滑动确保到达底部
    for (var i = 0; i <= 4; i++) {
        // 从屏幕下方向上滑动
        swipe(screenWidth / 2, screenHeight * 0.8, screenWidth / 2, screenHeight * 0.2, 800);
        sleep(1000);

        // 检查是否已经到底（可以检查是否有新的内容加载）
        // 这里可以添加判断是否到达底部的逻辑
    }

    console.log("已完成滑动操作");
}


// 简化版本 - 基于实际测试结果
function chooseRealClickableButton() {
    var waiqinObj = selector().text("外勤打卡").findOne(1000);
    var kaoqinObj = selector().text("考勤打卡").findOne(1000);

    // 根据你的实际测试结果，外勤打卡是可以点击的
    if (waiqinObj && waiqinObj.visibleToUser()) {
        var bounds = waiqinObj.bounds();
        // 检查是否在屏幕内
        if (bounds.centerX() >= 0 && bounds.centerX() <= device.width &&
            bounds.centerY() >= 0 && bounds.centerY() <= device.height) {
            log("选择外勤打卡按钮（根据实际测试结果）");
            return waiqinObj;
        }
    }

    // 备用选择
    if (kaoqinObj && kaoqinObj.clickable() && kaoqinObj.visibleToUser()) {
        log("选择考勤打卡按钮");
        return kaoqinObj;
    }

    // 如果以上都不行，选择第一个找到的
    if (waiqinObj) {
        log("备选：外勤打卡");
        return waiqinObj;
    }

    if (kaoqinObj) {
        log("备选：考勤打卡");
        return kaoqinObj;
    }

    log("未找到任何按钮");
    return null;
}


function findAndVerifyClickableButton() {
    // 首先获取两个按钮对象
    var waiqinObj = selector().text("外勤打卡").findOne(1000);
    var kaoqinObj = selector().text("考勤打卡").findOne(1000);

    var candidates = [];

    // 收集候选按钮并进行详细分析
    if (waiqinObj) {
        candidates.push({
            element: waiqinObj,
            name: "外勤打卡",
            info: analyzeElementComprehensively(waiqinObj, 25)
        });
    }

    if (kaoqinObj) {
        candidates.push({
            element: kaoqinObj,
            name: "考勤打卡",
            info: analyzeElementComprehensively(kaoqinObj, 8)
        });
    }

    // 尝试实际点击测试
    for (var i = 0; i < candidates.length; i++) {
        var candidate = candidates[i];
        log("测试 " + candidate.name + " 是否真正可点击...");

        if (verifyElementClickability(candidate.element, candidate.name)) {
            log("确认 " + candidate.name + " 是真正可点击的按钮");
            return candidate.element;
        }
    }

    // 如果点击测试都失败，回退到基于属性的判断
    log("点击测试失败，回退到基于属性的判断");
    return selectBasedOnAttributes(candidates);
}

function analyzeElementComprehensively(obj, depth) {
    var bounds = obj.bounds();
    var info = {
        visible: obj.visibleToUser(),
        clickable: obj.clickable(),
        focusable: obj.focusable(),
        enabled: obj.enabled(),
        depth: depth,
        bounds: bounds,
        size: {
            width: bounds.width(),
            height: bounds.height()
        },
        position: {
            centerX: bounds.centerX(),
            centerY: bounds.centerY()
        },
        inScreen: isInScreenBounds(bounds)
    };

    log("=== 元素综合分析 ===");
    log("可见性: " + info.visible);
    log("可点击: " + info.clickable);
    log("可获得焦点: " + info.focusable);
    log("启用状态: " + info.enabled);
    log("深度: " + info.depth);
    log("尺寸: " + info.size.width + "x" + info.size.height);
    log("屏幕内: " + info.inScreen);

    return info;
}

function verifyElementClickability(element, name) {
    try {
        var bounds = element.bounds();
        var centerX = bounds.centerX();
        var centerY = bounds.centerY();

        // 检查元素是否具备点击的基本条件
        if (element.clickable() && element.visibleToUser()) {
            // 检查坐标是否在屏幕范围内
            if (centerX >= 0 && centerX <= device.width &&
                centerY >= 0 && centerY <= device.height) {
                log(name + " 具备点击条件，坐标:(" + centerX + "," + centerY + ")");
                return true;
            } else {
                log(name + " 坐标不在屏幕范围内");
            }
        } else {
            log(name + " 属性表明不可点击 - 可点击:" + element.clickable() +
                " 可见:" + element.visibleToUser());
        }
    } catch (e) {
        log(name + " 检查过程中出现异常: " + e);
    }

    return false;
}

function selectBasedOnAttributes(candidates) {
    // 基于属性的评分系统
    var scoredCandidates = [];

    for (var i = 0; i < candidates.length; i++) {
        var candidate = candidates[i];
        var info = candidate.info;
        var score = 0;

        // 评分标准
        if (info.visible) score += 100;
        if (info.clickable) score += 80;
        if (info.focusable) score += 60;
        if (info.enabled) score += 40;
        if (info.inScreen) score += 30;

        // 深度得分（越浅越好）
        score += Math.max(0, 50 - info.depth);

        // 尺寸得分（合理的尺寸更好）
        if (info.size.width > 20 && info.size.height > 20) {
            score += 50;
        } else if (info.size.width > 10 && info.size.height > 10) {
            score += 25;
        }

        scoredCandidates.push({
            element: candidate.element,
            name: candidate.name,
            score: score,
            info: info
        });
    }

    // 按分数排序
    scoredCandidates.sort(function (a, b) {
        return b.score - a.score;
    });

    if (scoredCandidates.length > 0) {
        log("基于属性选择: " + scoredCandidates[0].name + " (得分: " + scoredCandidates[0].score + ")");
        return scoredCandidates[0].element;
    }

    return null;
}

function isInScreenBounds(bounds) {
    return bounds.left >= 0 && bounds.top >= 0 &&
        bounds.right <= device.width && bounds.bottom <= device.height;
}

// 使用示


// swipeToBottom(1);

//app应用关闭
function closeApp2(appPackgeName) {
    app.openAppSetting(appPackgeName);
    sleep(random(1000, 2000));
    while(!click("强制停止"));
}

// back();

// closeApp("com.weaver.emobile7");

log("子线程..");
launchApp("QQ"); // com.tencent.mobileqq
sleep(2000);
log("打开QQ..");
home();

sleep(2000);

runtime.accessibilityBridge.getService().performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_LOCK_SCREEN);


